const TOOLBAR = [{
	content: "新增",
	icon: "el-icon-document-add",
	type: "primary"
}, {
	content: "删除",
	icon: "el-icon-document-remove",
	type: "danger"
}];
const COLUMNS = [
    {
		prop: "id",
		label: "单号",
		width: "80"
	},
	{
		prop: "createTime",
		label: "创建时间",
		width: "100"
	},
	{
		prop: "applicant",
		label: "申请人",
		width: "80"
	},
	{
		prop: "name",
		label: "标题",
		width: "80"
	},
	{
		prop: "remake",
		label: "说明",
		width: "150"
	},
	{
		prop: "matter",
		label: "事项",
		width: "80"
	},
	{
		prop: "status",
		label: "状态",
		width: "80"
	},
	{
		prop: "auditleader",
		label: "发起部门审批人",
		width: "120"
	},
	{
		prop: "leader",
		label: "协助部门主管",
		width: "120"
	},
	{
		prop: "enddate",
		label: "截止日期",
		width: "120"
	},
	{
		prop: "updateTime",
		label: "更新日期",
		width: "120"
	}
];
const PCOLUMNS = [{
		prop: "username",
		label: "姓名",
		width: "40"
	}

];
const transFormrules = {
	enddate: [{
		required: true,
		message: '请选择服务到期时间',
		trigger: 'blur'
	}],
	applicantId:[{
		required: true,
		message: '请选择申请人',
		trigger: 'blur'	
	}],
	auditleaderId:[{
		required: true,
		message: '请选择本部门审核人',
		trigger: 'blur'		
	}],
	leaderId: [{
		required: true,
		message: '请选择负责人名字',
		trigger: 'blur'
	}],
	name: [{
		required: true,
		message: '请选择标题',
		trigger: 'blur'
	}]
}
const innerworkorderDetailFormrules = {
	matter: [{
		required: true,
		message: '请选择事项',
		trigger: 'blur'
	}],
	status: [{
		required: true,
		message: '请选择状态',
		trigger: 'blur'
	}],
	endTime: [{
		required: true,
		message: '请选择截止日期',
		trigger: 'blur'
	}],
	chargerId: [{
		required: true,
		message: '请选择负责人',
		trigger: 'blur'
	}]
}

let app = new Vue({
	el: "#app",
	// router: router,
	data() {
		return {
			timestamp: new Date().getTime(),
			uploadurl: axios.defaults.baseURL + "api/innerworkorderdetailform/annex/upload/",
			uploadtransformurl: axios.defaults.baseURL + "api/innerworkorderform/annex/upload/",
			headers: {
				Token: localStorage.getItem('TOKEN'),
				UserID: localStorage.getItem('USERID')
			},
			fileList: [],
			submitDisable: false,
			imgdialogImageUrl: "",
			submitEditDisable: false,
			imgdialogVisible: false,
			dialoginnerworkorderFormVisible: false,
			combinationForm: {
				defaultProps: {
					children: 'children',
					label: 'label'
				},

			},
			stateoptions: STATETYPE,
			teamLink: "i am copy",
			leftbar_show: true,
			// 添加、编辑标识
			action: "",
			dialogEditFormVisible: false,
			dialogItemFormVisible: false,
			tableHeight: window.innerHeight - 180,
			toolbar: TOOLBAR,
			tablecolums: COLUMNS,
			downloadForm:{},
			queryForm: {
				userid: localStorage.getItem('USERID'),
				keyword: "",
				name: "",
				matter: "",
				status: "",
				charger: "",
				endTime: [],
				createTime: [],
				updateTime: [],
				pageNo: 1, // 当前页码
				pagesize: 100, // 每页记录数
				pagesizes: [10, 20, 50, 100]
			},
			transForm: {

			},
			innerworkorderForm: {

			},
			innerworkorderDetailForm: {

			},
			querydeptForm: {
				deptid: localStorage.getItem('DEPTID'),
			},
			transFormOrg: [],
			pagepersontotal: 0,
			pagepersontotaltemp: 0,
			pagetotal: 0,
			ifdisabled:false,
			pagetotaltemp: 0,
			pickerOptions: {
				shortcuts: [{
					text: '最近一周',
					onClick(picker) {
						const end = new Date();
						const start = new Date();
						start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
						picker.$emit('pick', [start, end]);
					}
				}, {
					text: '最近一个月',
					onClick(picker) {
						const end = new Date();
						const start = new Date();
						start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
						picker.$emit('pick', [start, end]);
					}
				}, {
					text: '最近三个月',
					onClick(picker) {
						const end = new Date();
						const start = new Date();
						start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
						picker.$emit('pick', [start, end]);
					}
				}]
			},
			//状态
			status: WORKORDERSTATUS,
			//领导
			users:[],
			//员工
			allusers: [],
			//本部门领导
			teamsLaeder:[],
			//服务名称
			servicenames: [],
			//待办事项
			handleitems: [],
			// 多选
			multipleSelection: [],
			pagedatatemp: [], // 当前页结果集
			pagedata: [], // 当前页结果集
			pagepersondatatemp: [], // 当前页用户结果集
			pagepersondata: [], // 当前页用户结果集
			loaded: false,
		}
	},
	methods: {
		//删除
		async removeitem() {
			try {
				let res = await axios.post('api/innerworkorder/removeitem', this.innerworkorderDetailForm);
				if (res.code === 200) {
					this.query();
					this.$message({
						type: 'success',
						message: '删除成功!'
					});
				} else {
					this.$message.error(res.message);
				}

			} catch (e) {
				this.$message.error('请求出错！', e.message);
			}

		},
		//删除
		remove(index, row) {
			this.$confirm('此操作将永久删除该信息, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.innerworkorderDetailForm = deepCopy(row)
				this.removeitem()

			}).catch(() => {
				this.$message({
					type: 'info',
					message: '已取消删除'
				});
			});
		},
		additem(index, row) {
			this.action = "additem"
			this.index = index;
			this.dialogItemFormVisible = true;
			this.fileList = [];
			this.innerworkorderDetailForm = {
				innerworkorderId: row.id,
				charger: "",
				chargerId: null,
				matter: "",
				status: "",
				endTime: "",
				leader: "",
				remake: "",
				evidence: []
			}
		},
		edititem(index, row) {
			this.action = "edititem"
			this.dialogItemFormVisible = true;
			this.innerworkorderDetailForm = deepCopy(row)
			this.fileList = this.innerworkorderDetailForm.evidence
			for (item in this.innerworkorderDetailForm.evidence) {
				this.fileList[item].url = DOWNLOAD_INNERWORKERORDER_PATH + "/" + this.innerworkorderDetailForm.innerworkorderId +
					"/" + this.innerworkorderDetailForm
					.id + "/" + this.innerworkorderDetailForm.evidence[item].name + "/" + localStorage.getItem('TOKEN')
			}
			this.createTempfilelist(this.fileList)
			this.innerworkorderDetailForm.evidence = this.tempfilelist
		},
		async itemcofirm() {
			this.submitDisable = true;
			this.$refs.innerworkorderDetailForm.validate(async valid => {
				if (valid) {

					const loading = this.$loading(LOAD_STYLE);
					try {
						let res = null;
						if (this.action == "additem") {
							//添加
							res = await axios.post('api/innerworkorder/additem', this.innerworkorderDetailForm);
						} else if (this.action == "edititem") {
							//编辑
							res = await axios.put('api/innerworkorder/edititem', this.innerworkorderDetailForm);
						}

						if (res.code === 200) {
							this.dialogItemFormVisible = false
							this.query()
							this.$message.success(res.message);
						} else {
							this.$message.error(res.message);
						}

					} catch (e) {
						this.$message.error('请求出错！', e.message);
					}

					// 关闭加载框
					loading.close();
				}
			})
			this.submitDisable = false;
		},
		// 审核
		audit(index, row) {
			this.ifdisabled=true
			this.action = "audit"
			this.index = index;
			this.dialogEditFormVisible = true;
			this.transForm = deepCopy(row)
			this.fileList = this.transForm.evidence
		},
		edit(index, row) {
			console.log(row)
			this.ifdisabled=false
			this.action = "edit"
			this.index = index;
			this.dialogEditFormVisible = true;
			this.transForm = deepCopy(row)
			console.log(this.transForm)
			this.fileList = this.transForm.evidence
		},
		// 是否显示审核
		showAudit(index, row) {
			if (row.auditleaderId == localStorage.getItem('USERID') && row.auditleaderStatus == "待审核") {
				return true;
			} else if (row.leaderId == localStorage.getItem('USERID') && row.leaderStatus == "待审核") {
				return true;
			} else {
				return false;
			}
		},
		// 驳回
		async nopass() {
			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			try {
				this.$confirm('确定要驳回当前内部事务单吗?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(async () => {
					// 驳回
					this.transForm.userid = localStorage.getItem('USERID');
					let res = await axios.put('api/innerworkorder/nopass', this.transForm);
					if (res.code === 200) {
						this.query();
						this.dialogEditFormVisible = false
						this.$message.success(res.message);
					} else {
						this.$message.error(res.message);
					}
				}).catch((e) => {
					if (e.message) this.Msg('error', e.message);
				});
			} catch (e) {
				this.$message.error('驳回出错！', e.message);
			}
			// 关闭加载框
			loading.close();
		
		},
		
		// 审核通过
		async cofirm() {
			this.$refs.transForm.validate(async valid => {
				if (valid) {
					// 显示加载框
					const loading = this.$loading(LOAD_STYLE);
					try {
						// 审核
						this.transForm.userid = localStorage.getItem('USERID');
						let res = await axios.put('api/innerworkorder/audit', this.transForm);
						if (res.code === 200) {
							this.$message.success(res.message);
							this.query();
							this.dialogEditFormVisible = false
						} else {
							this.$message.error(res.message);
						}
		
					} catch (e) {
						this.$message.error('审核出错！', e.message);
					}
					// 关闭加载框
					loading.close();
				}
			})
		},
		async editcofirm() {
			this.submitEditDisable = true;
			this.$refs.transForm.validate(async valid => {
				if (valid) {
					// 显示加载框
					const loading = this.$loading(LOAD_STYLE);
					try {
						let res = null;
						if (this.action == "add") {
							//添加
							res = await axios.post('api/innerworkorder/add', this.transForm);
						} else if (this.action == "edit") {
							//再分配
							res = await axios.put('api/innerworkorder/edit', this.transForm);
						}
						if (res.code === 200) {
							this.dialogEditFormVisible = false
							this.query()
							this.$message.success(res.message);
						} else {
							this.$message.error(res.message);
						}
					} catch (e) {
						this.$message.error('请求出错！', e.message);
					}

					// 关闭加载框
					loading.close();
				}
			})
			this.submitEditDisable = false;
		},
		// 取得所有用户列表
		async getAllUser() {
			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			try {
				let res = await axios.get('api/user/all');
				if (res.code === 200) {
					this.allusers = res.data;
				} else {
					this.$message.error(res.message);
				}
			} catch (e) {
				this.$message.error('取得所有用户列表请求出错！', e.message);
			}
		
			// 关闭加载框
			loading.close();
		
		},
		async initHandleItem() {
			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			try {
				let res = await axios.get('api/service/handleitem');
				if (res.code === 200) {
					this.handleitems = res.data;
					this.handleitems = []
					if (this.handleitems.length > 0) {

					}
				} else {
					this.$message.error(res.message);
				}
			} catch (e) {
				this.$message.error('请求出错！', e.message);
			}

			// 关闭加载框
			loading.close();

		},
		async initServiceName() {
			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			try {
				let res = await axios.get('api/service/servicename');
				if (res.code === 200) {
					this.servicenames = res.data;
					if (this.servicenames.length > 0) {

					}
				} else {
					this.$message.error(res.message);
				}
			} catch (e) {
				this.$message.error('请求出错！', e.message);
			}

			// 关闭加载框
			loading.close();
		},

		//取得使用者部门主管
		async getLeader() {
			try {
				let res = await axios.post('api/userleader/dept', this.querydeptForm);
				if (res.code === 200) {
					this.teamsLaeder = res.data;
				} else {
					this.$message.error(res.message);
				}
			} catch (e) {
				this.$message.error('主管列表请求出错！', e.message);
			}
		},

		// 取得组织结构
		async getCombination() {
			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			try {
				let res = await axios.get('api/detp/combination');
				if (res.code === 200) {
					this.combinationForm.data = res.data;
				} else {
					this.$message.error(res.message);
				}
			} catch (e) {
				this.$message.error('组织结构请求出错！', e.message);
			}

			// 关闭加载框
			loading.close();
		},

		toolAction(acName) {
			if (acName == "删除") {
				this.removeconfirm();
			} else if (acName == "新增") {
				this.addinit();
			}
		},
		addinit() {
			this.action = "add"
			this.ifdisabled =false;
			this.dialogEditFormVisible = true;
			this.transForm = {
				enddate: "",
				evidence: [],
				applicantId:null,
				auditleaderId:null,
				leaderId: null,
				remake: "",
			}

		},
		removeconfirm() {
			if (this.multipleSelection.length > 0) {

				if (true) {
					this.$confirm('选择行中有多条数据，确定要将数据删除吗?', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					}).then(async () => {
						this.removemul()
					}).catch((e) => {
						this.$message({
							type: 'info',
							message: '已取消删除'
						});
					});
				} else {

				}
			} else {
				this.$message.error('请选择数据行！');
			}
		},
		async removemul() {
			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			try {
				let ids = []
				for (let row of this.multipleSelection) {
					ids.push(row.id)
				}
				let param = {
					"ids": ids
				}
				let res = await axios.post('api/innerworkorder/removemul', param);
				if (res.code === 200) {
					this.$message.success(res.message);
					this.query();
					//this.dialogAssigneFormVisible = false
				} else {
					this.$message.error(res.message);
				}
			} catch (e) {
				this.$message.error('请求出错！', e.message);
			}
			// 关闭加载框
			loading.close();
		},
		// 显示侧边栏
		showLeftBar() {

			if (this.leftbar_show)
				return this.leftbar_show = false
			if (!this.leftbar_show)
				return this.leftbar_show = true

		},
		// 表格多选 
		handleSelectionChange(val) {
			this.multipleSelection = val;
		},


		// 检查数据是否有修改
		checkDataChanged() {
			// 比对数据有无发生变化
			for (let key in this.testpaperForm) {
				if (this.testpaperForm[key] != this.testpaperFormOrg[key]) {
					return true;
				}
			}
			return false;
		},

		start() {
			this.queryForm.pageNo = 1
			this.query()
		},

		// 查询
		async query() {
			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			try {
				let res = await axios.post('api/innerworkorder/querylist', this.queryForm);
				if (res.code === 200) {
					this.pagedata = res.data;
					this.pagetotal = res.total;
					this.$message.success(res.message);
				} else {
					this.$message.error(res.message);
				}
			} catch (e) {
				this.$message.error('请求出错！', e.message);
			}
			// 关闭加载框
			loading.close();
		},



		selectionChange(selection) {
			this.selection = selection
		},



		// 设定表格当前页
		handleCurrentPageChange(selectedPageNo) {
			this.queryForm.pageNo = selectedPageNo
			// 加载数据页
			this.query()
		},
		//设定每页记录数
		handleSizeChange(val) {
			this.queryForm.pagesize = val
			// 加载数据页
			this.query()
		},
		// 设定表格当前页
		handlePersonCurrentPageChange(selectedPageNo) {
			this.queryPersonForm.pageNo = selectedPageNo
			// 加载数据页
			this.queryPerson()
		},
		//设定每页记录数
		handlePersonSizeChange(val) {
			this.queryPersonForm.pagesize = val
			// 加载数据页
			this.queryPerson()
		},
		handlemainRemove(file, fileList) {
			this.createTempfilelist(fileList);
			this.transForm.evidence = this.tempfilelist
		},
		handleRemove(file, fileList) {
			this.createTempfilelist(fileList);
			this.innerworkorderDetailForm.evidence = this.tempfilelist
		},
		handledownloadPreview(file) {
			console.log(file)
			this.imgdialogImageUrl = file.url;
			this.imgdialogVisible = true;
		},
		handlemaindownloadPreview(file){
			console.log(file.name)
			this.downloadFile(file.name)
		},
		//upload系列
		handlemainAvatarSuccess(res, file, filelist) {
			this.createTempfilelist(filelist);
			this.transForm.evidence = this.tempfilelist
			console.log(this.transForm)
		},
		handleAvatarSuccess(res, file, filelist) {
			this.createTempfilelist(filelist);
			this.innerworkorderDetailForm.evidence = this.tempfilelist
		},
		beforeAvatarUpload(file) {
			const isJPG = ["image/jpeg", "image/jpg", "image/png"].indexOf(file.type) > -1;
			const isLt2M = file.size / 1024 / 1024 < 2;
			if (!isJPG) {
				this.$message.error('图片只能是png,jpeg,jpg格式!');
				return false;
			}
			if (!isLt2M) {
				this.$message.error('上传图片大小不能超过 2MB!');
				return false;
			}
			return true;
		},
		createTempfilelist(filelist) {

			this.tempfilelist = []
			for (let s of filelist) {
				if (typeof(s.response) != "undefined") {
					this.tempfilelist.push({
						//name: s.response.data.name,
						url: "",
						name: s.name,
					});
				} else {
					this.tempfilelist.push({
						url: "",
						name: s.name,
					});
				}
				
			}
			console.log(this.tempfilelist)
		},
				//下载流传单附件
				async downloadFile(filename){
					this.downloadForm.downloadname = filename;
					this.downloadForm.token = localStorage.getItem('TOKEN');
					 let res = await axios.post('api/workorderinner/annex/download',this.downloadForm,'blob')
					 if(res){
					  const blData = res //拿到blob数据
					  const urlObjData = window.URL.createObjectURL(new Blob([res]))
					  //获取文件 进行下转码	  
					  const fileName = this.downloadForm.downloadname
					   
					  //创建a标签 点击a标签 达到下载目的
					  const link = document.createElement('a')
					  link.href = urlObjData
					  link.download = fileName //下载文件的名字
					  document.body.appendChild(link)
					  link.click()
					   
					  document.body.removeChild(link)
					  window.URL.revokeObjectURL(urlObjData);
					   
					 }
				},
		// 取得所有主管
		async getAllLeader() {
			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			try {
				let res = await axios.get('api/leader/all');
				if (res.code === 200) {
					this.users = res.data;
				} else {
					this.$message.error(res.message);
				}
			} catch (e) {
				this.$message.error('请求出错！', e.message);
			}
			}
		
	},
	async mounted() {
		// 自动调整表格高度
		window.onresize = () => {
				return (() => {
					this.tableHeight = window.innerHeight - 180
				})()
			},
			//初始化部门主管
			this.getLeader();
		//初始组织结构
		this.getCombination();
		//初始化员工列表
		this.getAllUser();
		//初始化所有部门领导
		this.getAllLeader();
		//初始化服务名称
		this.initServiceName();
		//初始化待办理事项
		//this.initHandleItem();
	}

});
